﻿Friend Class ListViewItemComparer
    Implements IComparer

    Private ReadOnly m_iColumn As Integer
    Private ReadOnly m_bAscendingOrder As Boolean = True
    Private ReadOnly m_eCompareType As CompareType

    Public Enum CompareType
        [String]
        Int
    End Enum

    Public Sub New(column As Integer, bAscendingOrder As Boolean, eCompareType As CompareType)
        m_iColumn = column
        m_bAscendingOrder = bAscendingOrder
        m_eCompareType = eCompareType
    End Sub

    ''' <summary>
    ''' Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
    ''' 
    ''' If the item in the x parameter is less than the item in the y parameter, a value less than zero is 
    ''' returned. If the items are identical, a zero is returned. Finally, if the item in the x parameter 
    ''' is greater than the item in the y parameter, a value greater than zero is returned.
    ''' </summary>
    ''' <param name="x">The first object to compare.</param>
    ''' <param name="y">The second object to compare.</param>
    ''' <returns>
    ''' Value Condition Less than zero x is less than y. Zero x equals y. Greater than zero x is greater than y.
    ''' </returns>
    ''' <exception cref="T:System.ArgumentException">Neither x nor y implements the <see cref="T:System.IComparable"></see> interface.-or- x and y are of different types and neither one can handle comparisons with the other. </exception>
    Public Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare
        Try
            Dim iReturnValue As Integer
            Dim szRowOneText As String
            Dim szRowTwoText As String

            If m_bAscendingOrder Then
                szRowOneText = DirectCast(x, ListViewItem).SubItems(m_iColumn).Text
                szRowTwoText = DirectCast(y, ListViewItem).SubItems(m_iColumn).Text
            Else
                szRowOneText = DirectCast(y, ListViewItem).SubItems(m_iColumn).Text
                szRowTwoText = DirectCast(x, ListViewItem).SubItems(m_iColumn).Text
            End If

            Select Case m_eCompareType
                Case CompareType.Int
                    iReturnValue = CInt(szRowOneText).CompareTo(CInt(szRowTwoText))
                    Exit Select
                Case CompareType.String
                    'String Comparison
                    iReturnValue = String.Compare(szRowOneText, szRowTwoText, True)
                    Exit Select
                Case Else
                    ' Throw New ApplicationException(String.Format("Unknown Compare Type: {0}", m_eCompareType))
                    Return 0
            End Select
            Return iReturnValue
        Catch
            Return 0
        End Try
    End Function
End Class
